package com.example.imagetest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ImageDownLoadAndShowActivity extends AppCompatActivity {

    private static final String TAG = "ImageDownLoadAndShowActivity";
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_down_load_and_show);

        // 检查是否有写入外部存储的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            // 如果已经有权限，那么直接去下载图片
            downloadImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 检查权限请求的结果
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 如果权限授予，则开始下载图片
                downloadImage();
            } else {
                // 如果权限拒绝，那么旧纪录错误日志
                Log.e(TAG, "Permission denied");
            }
        }
    }

    /**
     * 下载图片并进行展示
     */
    private void downloadImage() {
        OkHttpClient client = new OkHttpClient();
        // String url = "https://img.51miz.com/Element/01/02/75/76/c739ae8e_E1027576_0af26ea9.jpg";
        String url = "http://192.168.1.228:9000/image/22.jpg"; // 需要提前开minio服务器
        // String url = "https://www.baidu.com/img/bd_logo1.png";

        // 创建请求对象
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 异步调用enqueue方法来发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败时回调
                e.printStackTrace();
                Log.e(TAG, "下载图片失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功时回调
                if (response.isSuccessful()) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        inputStream = response.body().byteStream();

                        // 使用MediaStore API保存图片到公共媒体库
                        ContentValues values = new ContentValues();
                        values.put(MediaStore.Images.Media.DISPLAY_NAME, "downloaded_image.jpg");
                        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                        values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

                        Uri externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        Uri uri = getContentResolver().insert(externalUri, values);
                        if (uri != null) {
                            // 打开uri对应的输出流
                            outputStream = getContentResolver().openOutputStream(uri);

                            byte[] buffer = new byte[2048];
                            int bytesRead;
                            // 将输入流写入文件输出流
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }

                            // 查询保存的图片的实际路径
                            String[] projection = { MediaStore.Images.Media.DATA };
                            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                            String filePath = null;
                            if (cursor != null && cursor.moveToFirst()) {
                                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                filePath = cursor.getString(columnIndex);
                            }
                            if (cursor != null) {
                                cursor.close();
                            }
                            Log.d(TAG, "图片保存绝对路径：" + filePath);

                            // 更新系统媒体库
                            MediaScannerConnection.scanFile(ImageDownLoadAndShowActivity.this,
                                    new String[]{uri.toString()}, null, (path, uri1) -> {
                                        Log.d(TAG, "图片保存并更新到媒体库成功：" + path);
                                    });

                            // 在主线程上更新UI以显示下载的图片
                            runOnUiThread(() -> displayImage(uri.toString()));

                            // String finalFilePath = filePath;
                            // runOnUiThread(() -> displayImage1(finalFilePath));
                            // 记录图片保存的位置
                            Log.d(TAG, "图片保存相对URI路径：" + uri.toString());
                        } else {
                            Log.e(TAG, "图片保存失败，uri为空");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "图片保存失败: " + e.getMessage());
                    } finally {
                        // 关闭输入流和输出流
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }
                } else {
                    Log.e(TAG, "请求失败，响应码: " + response.code());
                }
            }
        });
    }


    /**
     * 在UI层显示图片
     *
     * @param imagePath
     */
    private void displayImage1(String imagePath) {
        ImageView imageView = findViewById(R.id.imageView);
        // 将图片文件解码为Bitmap
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        // 显示下载的图片
        imageView.setImageBitmap(bitmap);
    }

    /**
     * 在UI层显示图片
     *
     * @param imagePathOrUri 图片的文件路径或者Content Uri
     */
    private void displayImage(String imagePathOrUri) {
        ImageView imageView = findViewById(R.id.imageView);
        Bitmap bitmap = null;

        // 如果是Content Uri，则需要查询真实文件路径
        if (imagePathOrUri.startsWith("content://")) {
            try {
                // 查询真实的文件路径
                String[] projection = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(Uri.parse(imagePathOrUri), projection, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    String filePath = cursor.getString(columnIndex);
                    bitmap = BitmapFactory.decodeFile(filePath);
                }
                if (cursor != null) {
                    cursor.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 直接使用文件路径加载Bitmap
            bitmap = BitmapFactory.decodeFile(imagePathOrUri);
        }

        // 显示下载的图片
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            Log.e(TAG, "无法加载图片: " + imagePathOrUri);
        }
    }

}

/**
 *
 */